package com.zoo.diannaopeijian.config.shiro;

import com.zoo.diannaopeijian.domain.Staff;
import com.zoo.diannaopeijian.service.StaffService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * shiro Realm类
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private StaffService staffService;

    /**
     * 角色与权限认证
     * 暂无实现，直接返回null
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");

        //获取用户的输入的账号.
        Integer staffId = Integer.parseInt((String)authenticationToken.getPrincipal());
        System.out.println(authenticationToken.getCredentials());

        //通过staffId从数据库中查找 Staff对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        Staff staff = staffService.getStaffById(staffId);

        if (staff == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                staff, //用户名
                staff.getStaffPwd(), //密码
                ByteSource.Util.bytes(staff.getStaffPwdSalt()),
                getName()  //realm name
        );

        return authenticationInfo;
    }
}
